package cn.iocoder.yudao.module.book.controller.app.readBook;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.book.controller.app.readBook.vo.AppbookImagesRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.audio.AudioDO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.iocoder.yudao.module.book.service.images.bookImagesService;
import cn.iocoder.yudao.module.book.service.audio.AudioService;
import cn.iocoder.yudao.module.book.service.users.userDTOService;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Tag(name = "用户 APP - 绘本阅读")
@RestController
@RequestMapping("/api/user/book")
public class AppReadBookController {

    @Resource
    private bookImagesService bookImageService;

    @Resource
    private AudioService audioService;

    @Resource
    private userDTOService userService;


    @GetMapping("/read")
    @Operation(summary = "绘本阅读")
    public CommonResult<List<AppbookImagesRespVO>> readBook(@Valid @RequestParam("bookId") Integer bookId) {
        try {
            List<AppbookImagesRespVO> pages = bookImageService.getBookImagesByBookId(bookId);
            if (pages == null) {
                return CommonResult.success(null);
            }
            try {
                Long userId = userService.getCurrentUserId();
                if (userId != null) {
                    for (int i = 0; i < pages.size(); i++) {
                        AudioDO rec = audioService.getLatestRecording(userId, Long.valueOf(bookId), i);
                        if (rec != null && rec.getAudioData() != null && rec.getAudioData().length > 0) {
                            String streamUrl = "/app-api/api/user/listen/stream?bookId=" + bookId + "&page=" + i + "&uid=" + userId;
                            pages.get(i).setMyAudioUrl(streamUrl);
                        }
                    }
                }
            } catch (Exception ignore) {}
            return CommonResult.success(pages);
        } catch (Exception e) {
            // 避免 500，返回空列表
            return CommonResult.success(null);
        }
    }

    @GetMapping("/markRead")
    @Operation(summary = "标记绘本为已读")
    public CommonResult<Boolean> markRead(@Valid @RequestParam("bookId") Integer bookId) {
        return CommonResult.success(bookImageService.markRead(bookId));
    }

//    @GetMapping("/markRead")
//    @Operation(summary = "标记绘本为已读")
//    public CommonResult<Boolean> markRead(@Valid @RequestParam Integer bookId) {
//        return CommonResult.success(bookImageService.markRead(bookId));
//    }

}
